/**
 * Created by zy on 2016/7/8.
 * 生成维修项目 - 缺项维修建议
 */


;(function ($, window, document, undefined) {

    /***---------- 表单项 start ----------***/
    // 初始提交数据
    var initData = function () {
        var temp = $('#JQ_post_data').html();
        temp = eval('(' + temp + ')');
        return temp;
    }();
    // 缺陷个数
    var $defect_count = $('#JQ_defect_count');
    // 项目名称
    var $name = $('#JQ_project_name');
    // 施工单位
    var $company = $('#JQ_company');
    // 管道
    var $pipe_select = $('#JQ_pipe_name').select3({
        usable: false,
        data: [{id: initData.pipeId, text: initData.pipeName}]
    });
    // 起点位置
    var $begin_select = $('#JQ_begin_name').select3({
        usable: false,
        data: [{id: initData.beginId, text: initData.beginName, mile: initData.beginMile}]
    });
    // 终点位置
    var $end_select = $('#JQ_end_name').select3({
        usable: false,
        data: [{id: initData.endId, text: initData.endName, mile: initData.endMile}]
    });
    // 开工时间
    var $begin_date = $('#JQ_begin_date');
    // 竣工时间
    var $end_date = $('#JQ_end_date');
    // 新建表单 div
    var $form_table = $('#JQ_form_table');
    // 隐藏表单 div
    var $form_list = $('#JQ_form_list');
    /***---------- 表单项 end ----------***/


    /***---------- 隐藏项 start ----------***/
    // 管道
    var $pipe_gather = $('#JQ_pipe_gather').select3({
        usable: false,
        data: [{id: initData.pipeId, text: initData.pipeName}]
    });
    // 起点位置
    var $begin_gather = $('#JQ_begin_gather').select3({
        usable: false,
        data: [{id: initData.beginId, text: initData.beginName, mile: initData.beginMile}]
    });
    // 终点位置
    var $end_gather = $('#JQ_end_gather').select3({
        usable: false,
        data: [{id: initData.endId, text: initData.endName, mile: initData.endMile}]
    });
    // 缺陷类型
    var $defect_type = $('#JQ_defect_type').select3({
        search: false
    });
    // 建议最迟维修时间 - 1
    var $repair_date_begin = $('#JQ_repair_date_begin');
    // 建议最迟维修时间 - 1
    var $repair_date_end = $('#JQ_repair_date_end');
    // 工作量
    var $work_form = $('#JQ_work_form');

    // 填充缺陷类型
    DyyBase.ajax(defectApi.url_defect_class(), {}, function (dataset) {
        var json = DyyBase.getSelect(dataset);
        $defect_type.add(json);
    });

    // 已选择的缺陷列表
    var $selected_defect = $('#JQ_selected_defect').checkbox3(), DTSELECT;
    // 被排除的缺陷列表
    var $list_gather = $('#JQ_list_gather').checkbox3(), DTGATHER;

    // 查询对象
    var filter = {
        // 新建表单
        getForm: function () {
            var data = {};
            data.mode = true;
            data.name = function () {
                var v = $.trim($name.val());
                if (v) {
                    return v;
                } else {
                    data.mode = false;
                    $name.TIP({content: '项目名称不能为空!'});
                }
                return '';
            }();
            data.assemblyCompany = function () {
                var v = $.trim($company.val());
                if (v) {
                    return v;
                } else {
                    data.mode = false;
                    $company.TIP({content: '施工单位不能为空!'});
                }
                return '';
            }();
            data.planStartDate = function () {
                var v = $.trim($begin_date.val());
                if (v) {
                    return v;
                }
                return '';
            }();
            data.planCompletionDate = function () {
                var v1 = $.trim($begin_date.val());
                var v2 = $.trim($end_date.val());
                if (v2) {
                    if (v1) {
                        if (!(Dyy.checkDateLate(v1, v2))) {
                            data.mode = false;
                            $end_date.TIP({content: '竣工时间须晚于开工时间!'});
                        }
                    }
                    return v2;
                }
                return '';
            }();
            data.pipeLineId = function () {
                var v = $pipe_select.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.fromPointId = function () {
                var v = $begin_select.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.fromPointMileage = function () {
                var v = $begin_select.val('mile');
                if (v) {
                    return v;
                }
                return '';
            }();
            data.toPointId = function () {
                var v = $end_select.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.toPointMileage = function () {
                var v = $end_select.val('mile');
                if (v) {
                    return v;
                }
                return '';
            }();
            data.defectInfoId = function () {
                return initData.defectId;
            }();
            return data;
        },
        // 获取初始缺陷id
        getDefectId: function () {
            var data = {};
            data.defectInfoId = initData.defectId;
            data.searchType = function () {
                if (initData.defectId.length === 0) {
                    return 'empty';
                }
                return '';
            }();
            return DyyBase.convertToArr(data);
        },
        // 获得已选择ids
        getSelectedIds: function (flag) {
            var arr = [];
            var $chks = $selected_defect.find('i.zy-checkbox');
            if ($chks.length > 0) {
                $chks.each(function () {
                    var $this = $(this);
                    if (flag) {
                        if ($this.hasClass('active')) {
                            arr.push($this.attr('data-id'));
                        }
                    } else {
                        arr.push($this.attr('data-id'));
                    }
                });
            }
            return arr;
        },
        // 获得集合ids
        getGatherIds: function () {
            var arr = [];
            var $chks = $list_gather.find('i.zy-checkbox');
            if ($chks.length > 0) {
                $chks.each(function () {
                    var $this = $(this);
                    if ($this.hasClass('active')) {
                        arr.push($this.attr('data-id'));
                    }
                });
            }
            return arr;
        },
        // 查询参数
        getSearch: function () {
            var data = {};
            data.instTaskId = function () {
                return initData.instTaskId ? initData.instTaskId : '';
            }();
            data.pipeId = function () {
                return initData.pipeId ? initData.pipeId : '';
            }();
            data.beginMileage = function () {
                return initData.beginMileage ? initData.beginMileage : '';
            }();
            data.endMileage = function () {
                return initData.endMileage ? initData.endMileage : '';
            }();
            data.featureType = function () {
                var v = $defect_type.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.erf = function () {
                if ($('#JQ_erf').hasClass('active')) {
                    return '1.0';
                }
                return '';
            }();
            data.excludeDeIds = function () {
                return initData.defectId ? initData.defectId : '';
            }();
            data.latestBeginTime = function () {
                var v = $repair_date_begin.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.latestEndTime = function () {
                var v = $repair_date_end.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            return data;
        },
        // 获取保存&发布
        getSave: function () {
            var param = filter.getForm();
            if ($work_form.verify()) {
                var $input = $work_form.find('input[type="text"]');
                $input.each(function () {
                    var $this = $(this);
                    var name = $this.prop('name'), value = $this.val();
                    param[name] = value;
                });
            } else {
                param.mode = false;
            }
            return param;
        }
    };

    // 加载已选择的缺陷列表
    function loadSelected(flag) {
        if (flag) {
            if (DTSELECT) {
                DTSELECT.draw();
            }
        } else {
            if (!DTSELECT) {
                DTSELECT = $selected_defect.DataTable({
                    'language': {
                        'zeroRecords': DyyBase.defect_empty()
                    },
                    'info': false,
                    'autoWidth': false,
                    'serverSide': true,
                    'ordering': false,
                    'processing': false,
                    'searching': false,
                    'lengthChange': false,
                    'paging': false,
                    'pageLength': 1000,
                    'ajax': function (data, callback) {
                        var param = filter.getDefectId();
                        DyyBase.ajax(defectApi.url_advise_list(), param, function (dataset) {
                            var returnData = {};
                            returnData.draw = data.draw;
                            returnData.recordsTotal = 1000;
                            returnData.recordsFiltered = 1000;
                            returnData.data = DyyBase.clearNull(dataset.result);
                            callback(returnData);
                        });
                    },
                    'drawCallback': function () {
                        // 清空全选
                        $selected_defect.find('i.zy-checkbox-all').trigger('clear');
                        // 重新计数
                        $defect_count.trigger('changeCount');
                        // 填充工作量
                        fillWork();
                    },
                    'columns': [
                        {
                            data: 'defectId', render: function (data) {
                            return '<i class="zy-checkbox" data-id="' + data + '" title="选中"></i>';
                        }
                        },
                        {
                            data: 'pipeName', render: function (data) {
                            return '<span class="l" title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'featureSubType', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'mileage', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'length', render: function (data, type, row) {
                            return '<span title="' + data + '">' + data + '/' + row.width + '/' + row.depth + '</span>';
                        }
                        },
                        {
                            data: 'clock', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'erf', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'repairSuggestion', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'planRepairTime', render: function (data) {
                            return '<span title="' + Dyy.getDate(data) + '">' + Dyy.getDate(data) + '</span>';
                        }
                        },
                        {
                            data: 'planRepairType', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'defectId', render: function (data) {
                            return '<i data-id="' + data + '" class="zy-details-icon" title="展开详情"></i>';
                        }
                        }
                    ]
                });
            }
        }
    }

    // 查看缺陷列表
    $('#JQ_view_defect').click(function () {
        var param = filter.getForm();
        if (param.mode) {
            $(this).hide();
            $form_table.hide();
            $form_list.fadeIn();
            $('#JQ_delete_defect').show();

            $('#JQ_goback_list').hide();
            $('#JQ_goback_task').show();

            loadSelected();
        }
    });


    // 加载被排除了已选缺陷ID的列表
    function loadGather(flag) {
        if (flag) {
            if (DTGATHER) {
                DTGATHER.draw();
            }
        } else {
            if (!DTGATHER) {
                DTGATHER = $list_gather.DataTable({
                    'language': {
                        'zeroRecords': DyyBase.defect_empty()
                    },
                    'info': false,
                    'autoWidth': false,
                    'serverSide': true,
                    'ordering': false,
                    'processing': false,
                    'searching': false,
                    'lengthChange': false,
                    'paging': false,
                    'pageLength': 1000,
                    'ajax': function (data, callback) {
                        var param = DyyBase.convertToArr(filter.getSearch());
                        DyyBase.ajax(defectApi.url_advise_list(), param, function (dataset) {
                            var returnData = {};
                            returnData.draw = data.draw;
                            returnData.recordsTotal = 1000;
                            returnData.recordsFiltered = 1000;
                            returnData.data = DyyBase.clearNull(dataset.result);
                            callback(returnData);
                        });
                    },
                    'drawCallback': function () {
                        $list_gather.find('i.zy-checkbox-all').trigger('clear');
                    },
                    'columns': [
                        {
                            data: 'defectId', render: function (data) {
                            return '<i class="zy-checkbox" data-id="' + data + '" title="选中"></i>';
                        }
                        },
                        {
                            data: 'pipeName', render: function (data) {
                            return '<span class="l" title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'featureSubType', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'mileage', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'length', render: function (data, type, row) {
                            return '<span title="' + data + '">' + data + '/' + row.width + '/' + row.depth + '</span>';
                        }
                        },
                        {
                            data: 'clock', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'erf', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'repairSuggestion', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'planRepairTime', render: function (data) {
                            return '<span title="' + Dyy.getDate(data) + '">' + Dyy.getDate(data) + '</span>';
                        }
                        },
                        {
                            data: 'planRepairType', render: function (data) {
                            return '<span title="' + data + '">' + data + '</span>';
                        }
                        },
                        {
                            data: 'defectId', render: function (data) {
                            return '<i data-id="' + data + '" class="zy-details-icon" title="展开详情"></i>';
                        }
                        }
                    ]
                });
            }
        }
    }

    // 添加更多缺陷
    $('#JQ_add_more').click(function () {
        var $this = $(this);
        $this.toggleClass('active');
        if ($this.hasClass('active')) {
            $('#JQ_more_list').fadeIn();
            loadGather();
        } else {
            $('#JQ_more_list').hide();
        }
    });

    // 查询
    $('#JQ_search').click(function () {
        loadGather(true);
    });
    /***---------- 隐藏项 end ----------***/


    /***---------- 展开详情 start ----------***/
    // 详情模板
    var defectTemplate = [
        {name: 'pipeName', title: '管道名称：'},
        {name: 'customNumber', title: '缺陷编号：'},
        {name: 'featureSubType', title: '缺陷类型：'},
        {name: 'mileage', title: '绝对距离(m)：'},
        {
            name: 'length', title: '长/宽/深(mm)：', render: function (d, r) {
            return r.length + '/' + r.width + '/' + r.depth;
        }
        },
        {name: 'clock', title: '时钟位置：'},
        {name: 'erf', title: 'ERF：'},
        {name: 'repairSuggestion', title: '维修建议：'},
        {
            name: 'evaluateTime', title: '最迟维修时间：', render: function (d) {
            return Dyy.getDate(d);
        }
        },
        {name: 'planRepairType', title: '建议维修方法：'},
        {
            name: 'planRepairTime', title: '评价时间：', render: function (d) {
            return Dyy.getDate(d);
        }
        },
        {name: 'assessDepartment', title: '评价单位：'}
    ];

    // 展示详情 - 1
    $selected_defect.on('click', 'i.zy-details-icon', function () {
        DyyBase.showDetails($(this), DTSELECT, $selected_defect, defectTemplate);
    });

    // 展示详情 - 2
    $list_gather.on('click', 'i.zy-details-icon', function () {
        DyyBase.showDetails($(this), DTGATHER, $list_gather, defectTemplate);
    });
    /***---------- 展开详情 end ----------***/


    // 添加缺陷点
    $('#JQ_add').click(function () {
        var $this = $(this);
        var arr = filter.getGatherIds();
        if (arr.length > 0) {
            initData.defectId = initData.defectId.concat(arr);

            loadSelected(true);
            loadGather(true);
        } else {
            $this.MSG({
                content: '请选择要添加的缺陷点!'
            });
        }
    });

    // 删除缺陷点
    $('#JQ_delete_defect').click(function () {
        var $this = $(this);
        var arr = filter.getSelectedIds(true);
        if (arr.length > 0) {
            initData.defectId = DyyBase.deleteArray(initData.defectId, arr);

            loadSelected(true);
            loadGather(true);
        } else {
            $this.MSG({
                content: '请选择要删除的缺陷点!'
            });
        }
    });


    /***---------- 改变缺陷点数目 start ----------***/
    $defect_count.on('changeCount', function () {
        $defect_count.text(initData.defectId.length);
    });
    $defect_count.trigger('changeCount');
    /***---------- 改变缺陷点数目 end ----------***/


    /***---------- 填充工作量 start ----------***/
    // 填充工作量
    function fillWork() {
        DyyBase.ajax(defectApi.url_advise_work(), DyyBase.convertToArr({defectInfoId: initData.defectId}), function (dataset) {
            var param = DyyBase.clearNaN(dataset.result);
            var count = 0;
            for (var k in param) {
                var $input = $work_form.find('input[name="' + k + '"]');
                if ($input.length) {
                    $input.val(param[k]);
                    count += parseInt(param[k]);
                }
            }
            $work_form.find('input[name="total"]').val(count);
        });
    }
    fillWork();

    /***---------- 填充工作量 end ----------***/


    // 保存
    $('#JQ_save_task').click(function () {
        var $this = $(this);
        var param = filter.getSave();
        if(param.mode){
            param.dataStated = '01';
            DyyBase.ajax(defectApi.url_repair_step2(), DyyBase.convertToArr(param), function (dataset) {
                if (dataset.bool) {
                    $this.MSG({
                        type: 'success',
                        content: '保存维修项目成功!',
                        yesBtnAct: DyyBase.goToPage,
                        closeBtnAct: DyyBase.goToPage,
                        goToUrl: DyyBase.root_path + '/pbf/suggestion/toSuggest.html'
                    });
                } else {
                    $this.MSG({
                        type: 'error',
                        content: dataset.result
                    });
                }
            });
        }
    });

    // 发布
    $('#JQ_release_task').click(function () {
        var $this = $(this);
        var param = filter.getSave();
        if(param.mode){
            param.dataStated = '20';
            DyyBase.ajax(defectApi.url_repair_step2(), DyyBase.convertToArr(param), function (dataset) {
                if (dataset.bool) {
                    $this.MSG({
                        type: 'success',
                        content: '发布维修项目成功!',
                        yesBtnAct: DyyBase.goToPage,
                        closeBtnAct: DyyBase.goToPage,
                        goToUrl: DyyBase.root_path + '/pbf/suggestion/toSuggest.html'
                    });
                } else {
                    $this.MSG({
                        type: 'error',
                        content: dataset.result
                    });
                }
            });
        }
    });

    // 返回列表
    $('#JQ_goback_list').click(function () {
        window.location.href = DyyBase.root_path + '/pbf/suggestion/toSuggest.html';
    });

    // 返回上一步
    $('#JQ_goback_task').click(function () {
        $(this).hide();
        $('#JQ_goback_list').show();

        $form_table.fadeIn();
        $form_list.hide();

        $('#JQ_delete_defect').hide();
        $('#JQ_view_defect').show();
    });

    // 验证工作量
})(jQuery, window, document);